package com.easylinkin.linkappapi.personality.service.impl;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.service.CommonAdminService;
import com.easylinkin.linkappapi.personality.entity.Personality;
import com.easylinkin.linkappapi.personality.mapper.PersonalityMapper;
import com.easylinkin.linkappapi.personality.service.PersonalityService;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;

/**
 * <p>
 * 应用管理表 服务实现类
 * </p>
 *
 * @author XuGuoQing
 * @since 2020-05-19
 */
@Service
public class PersonalityServiceImpl extends ServiceImpl<PersonalityMapper, Personality> implements PersonalityService {
    private static final int NO_DELETE = 1;
    private static final String LEGAL = "LEGAL";
    @Resource
    private CommonAdminService commonAdminService;
    
    @Resource
	LinkappTenantService linkappTenantService;

    @Override
    public boolean addPersonality(Personality personality, String tenantId) {
        validParamFormat(personality);
        validRepeat(personality);
        commonAdminService.setCreateAndModifyInfo(personality);
        this.save(personality);
        if (ObjectUtils.isNotEmpty(tenantId)) {
            LinkappTenant tenant = new LinkappTenant();
            tenant.setId(tenantId);
            tenant = linkappTenantService.selectLinkappTenant(tenant);
            if (tenant != null) {
                tenant.setPersonalityId(personality.getId());
                linkappTenantService.updateLinkappTenant(tenant);
            }
        }
        return true;
    }

    @Override
    public boolean updatePersonality(Personality personality) {
        Assert.notNull(personality.getId(), "个性化模板id不能为空");
        validParamFormat(personality);
        Personality applicationExist = baseMapper.selectById(personality.getId());
        Assert.notNull(applicationExist, "根据id查找个性化模板不存在");
//        boolean isApplicationNameNotRepeat = !isPersonalityNameExist(personality.getName()) || personality.getName().equals(applicationExist.getName());
//        Assert.isTrue(isApplicationNameNotRepeat, "个性化应用名称不能重复");
//        boolean isApplicationDomainNotRepeat = !isDomainExist(personality.getDomin()) || personality.getDomin().equals(applicationExist.getDomin());
//        Assert.isTrue(isApplicationDomainNotRepeat, "域名不能重复");
        validRepeat(personality);
        commonAdminService.setModifyInfo(personality);
        return this.updateById(personality);
    }

    @Override
    public boolean deletePersonality(List<String> personalityList) {
        Assert.notEmpty(personalityList, "删除个性化模板列表不能为空");
        baseMapper.deleteBatchIds(personalityList);
        return true;
    }

    @Override
    public IPage<Personality> getPage(IPage page, Personality personality) {
        Assert.notNull(page, "分页数据不能为空");
        Assert.notNull(personality, "查询对象不能为空");
        QueryWrapper<Personality> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(personality.getName()), "name", personality.getName());
        wrapper.like(StringUtils.isNotEmpty(personality.getDomin()), "domin", personality.getDomin());
        wrapper.orderByDesc("modify_time");
        wrapper.and(e-> e.isNotNull("domin").or().isNotNull("name").or().isNotNull("platform"));
        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public Personality getPersonalIfoByDomain(String domain) {
        QueryWrapper<Personality> wrapper = new QueryWrapper<>();
        wrapper.eq("domin",domain); //全量匹配
//        wrapper.like("domin", domain);
        List<Personality>   personalityList  = baseMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(personalityList)){
            return  null;
        }
        return personalityList.get(0);
    }

    @Override
    public List<Personality> getList() {
        QueryWrapper<Personality> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("modify_time");
        List<Personality>   personalityList  = baseMapper.selectList(wrapper);

        return personalityList;
    }


//    /**
//     * 校验当前的个性化名称是否不存在
//     */
//    boolean isPersonalityNameExist(String applicationName) {
//        QueryWrapper<Personality> wrapper = new QueryWrapper<>();
//        wrapper.eq("name", applicationName);
//        List<Personality> applicationExist = this.list(wrapper);
//        return applicationExist.size() > 0;
//    }
//
//    /**
//     * 校验当前的域名是否存在
//     */
//    boolean isDomainExist(String domain) {
//        QueryWrapper<Personality> wrapper = new QueryWrapper<>();
//        wrapper.eq("domin", domain);
//        List<Personality> applicationExist = this.list(wrapper);
//        return applicationExist.size() > 0;
//    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(Personality personality) {
        Assert.isTrue(StringUtils.isNotBlank(personality.getPlatform()) && personality.getPlatform().length() <= 50, "平台名称不能空或者超长");
        Assert.isTrue(domainCheckLegal(personality.getDomin()).equals(LEGAL), domainCheckLegal(personality.getDomin()));
    }

    /**
     * 校验重复
     */
    private void validRepeat(Personality personality) {
        QueryWrapper<Personality> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", personality.getName());
        List<Personality> list = baseMapper.selectList(queryWrapper);
        if (list.size() != 0) {
            if (list.size() > 1) {
                throw new BusinessException("个性化应用名称有重复");
            }
            if (StringUtils.isEmpty(personality.getId()) || !personality.getId().equals(list.get(0).getId())) {
                throw new BusinessException("个性化应用名称已存在");
            }
        }
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("domin", personality.getDomin());
        list = baseMapper.selectList(queryWrapper);
        if (list.size() != 0) {
            if (list.size() > 1) {
                throw new BusinessException("个性化应用域名有重复");
            }
            if (StringUtils.isEmpty(personality.getId()) || !personality.getId().equals(list.get(0).getId())) {
                throw new BusinessException("个性化应用域名已存在");
            }
        }

    }

    public static String domainCheckLegal(String domain) {

        if (StringUtils.isEmpty(domain)) {
            return "域名不能为空!";
        }
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        String str = null;
//        String reg = "^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$";
        //https://www.baidu.com
        //http://192.168.0.61:8080
        String reg = "^(?=^.{3,255}$)(http(s)?:\\/\\/)?(www\\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\\d+)*(\\/\\w+\\.\\w+)*$";
        String regStr = "/(\\w+):\\/\\/([^/:]+)(:\\d*)?/";
        p = Pattern.compile(reg);
        m = p.matcher(domain);
        b = m.matches();
        if (!b) {
            p = Pattern.compile(regStr);
            m = p.matcher(domain);
            b = m.matches();
            if (!b) {
                return "不符合域名注册规定";
            }
        }
        return LEGAL;
    }

	@Override
	public Personality getPersonalityByTenant(String tenantId) {
		if(tenantId!=null) {
       	 LinkappTenant tenant = new LinkappTenant();
            tenant.setId(tenantId);
            tenant = linkappTenantService.selectLinkappTenant(tenant);
            
            if(tenant!=null && tenant.getPersonalityId()!=null) {
            	return this.getById(tenant.getPersonalityId());
            }
            return null;
       }
		return null;
	}

}
